package com.hll.controller;

import com.alibaba.fastjson.JSONObject;
import com.hll.pojo.Books;
import com.hll.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author: Mr.Hu
 * @create: 2021-03-12 22:48
 */
@Controller
@RequestMapping("/book")
public class BookController {
  /*注解配置bean的属性*/
  @Autowired private BookService bookService;

  @RequestMapping("/allBook")
  public String list(Model model) {
    List<Books> list = bookService.queryAllBook();
    model.addAttribute("list", list);
    return "allBook";
  }

  /*只做跳转页面的功能*/
  @RequestMapping("/toAddBook")
  public String toAddPaper() {
    return "addBook";
  }

  @RequestMapping("/addBook")
  public String addPaper(Books books) {
    System.out.println(books);
    bookService.addBook(books);
    return "redirect:/book/allBook";
  }

  @RequestMapping("/toUpdateBook")
  public String toUpdateBook(Model model, int id) {
    Books books = bookService.queryBookById(id);
    System.out.println(books);
    model.addAttribute("book", books);
    return "updateBook";
  }

  @RequestMapping("/updateBook")
  public String updateBook(Model model, Books book) {
    System.out.println(book);
    bookService.updateBook(book);
    Books books = bookService.queryBookById(book.getBookID());
    model.addAttribute("books", books);
    return "redirect:/book/allBook";
  }

  @RequestMapping("/del/{bookId}")
  public String deleteBook(@PathVariable("bookId") int id) {
    bookService.deleteBookById(id);
    return "redirect:/book/allBook";
  }

  /*@RestController 在类上加，那么返回的都是json*/
  @RequestMapping(value = "/json1", produces = "application/json;charset=utf-8")
  @ResponseBody
  public String json1() {
    Books books = new Books(1, "java", 2, "sda");
    // 将我们的对象解析成为json格式
    String str = JSONObject.toJSONString(books);
    // 由于@ResponseBody注解，这里会将str转成json格式返回；十分方便
    return str; // 相当于 response.getWriter.write(str);
  }
}
